package cn.innosmart.aq.bean;

import android.os.Parcel;
import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.innosmart.aq.util.DeviceConstant;
import cn.innosmart.aq.util.SystemConstant;

/**
 * Created by David on 2015/8/17.
 */
public class RuleBean {
    public int pns_priority; // 0-不推送， 1-普通，2-重要，3-非常重要
    private String pns;
    private JSONObject userdata = new JSONObject();
    private HashMap<Integer, JSONArray> timeLine;
    private String userTag;
    private String id;
    private String title;
    private String icon_data;
    private String icon_type;
    private int enabled;
    private int repeat_type;
    private String start;
    private String end;
    private int weekdays;
    private int pnsInterval;
    private String place;
    private HashMap<String, TriggerBean> triggers;
    private ArrayList<CommandBean> commands;

    public RuleBean() {

    }

    public RuleBean(JSONObject jsonObject) {
        JSONObject jsonTriggers = new JSONObject();
        try {
            this.id = jsonObject.getString("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            this.title = jsonObject.getString("title");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            this.place = jsonObject.getString("place");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            this.userdata = jsonObject.getJSONObject("user_data");
            this.start = userdata.getString("start");
            this.end = userdata.getString("end");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            this.weekdays = jsonObject.getInt("weekdays");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            this.repeat_type = jsonObject.getInt("repeat_type");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            this.enabled = jsonObject.getInt("enabled");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            this.icon_data = jsonObject.getString("icon_data");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            this.pns_priority = jsonObject.getInt("pns_priority");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            this.icon_type = jsonObject.getString("icon_type");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            this.userTag = jsonObject.getString("user_tag");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            JSONArray jsonTimeLine = jsonObject.getJSONArray("timeline");
            System.out.println("jsonTimeLine=" + jsonTimeLine.toString());
            timeLine = new HashMap<Integer, JSONArray>();
            for (int i = 0; i < jsonTimeLine.length(); i++) {
                JSONArray childeTimeLine = new JSONArray();
                try {
                    childeTimeLine = (JSONArray) jsonTimeLine.get(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (childeTimeLine.length() != 0) {
                    int startIndex = 0;
                    int endIndex = 0;
                    try {
                        startIndex = (int) childeTimeLine.get(0);
                        endIndex = (int) childeTimeLine.get(1);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (startIndex < 1 * 24 * 60) {
                        JSONArray jsonArray = timeLine.get(0);
                        childeTimeLine.put(0, startIndex);
                        childeTimeLine.put(1, endIndex);
                        timeLine.put(0, childeTimeLine);
                    } else if (startIndex < 2 * 24 * 60) {
                        childeTimeLine.put(0, startIndex);
                        childeTimeLine.put(1, endIndex);
                        timeLine.put(1, childeTimeLine);
                    } else if (startIndex < 3 * 24 * 60) {
                        childeTimeLine.put(0, startIndex);
                        childeTimeLine.put(1, endIndex);
                        timeLine.put(2, childeTimeLine);
                    } else if (startIndex < 4 * 24 * 60) {
                        childeTimeLine.put(0, startIndex);
                        childeTimeLine.put(1, endIndex);
                        timeLine.put(3, childeTimeLine);
                    } else if (startIndex < 5 * 24 * 60) {
                        childeTimeLine.put(0, startIndex);
                        childeTimeLine.put(1, endIndex);
                        timeLine.put(4, childeTimeLine);
                    } else if (startIndex < 6 * 24 * 60) {
                        childeTimeLine.put(0, startIndex);
                        childeTimeLine.put(1, endIndex);
                        timeLine.put(5, childeTimeLine);
                    } else if (startIndex < 7 * 24 * 60) {
                        JSONArray jsonArray = timeLine.get(6);
                        childeTimeLine.put(0, startIndex);
                        childeTimeLine.put(1, endIndex);
                        timeLine.put(6, childeTimeLine);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            this.pns = (String) jsonObject.getJSONArray("enabled_notifications").get(0);
        } catch (JSONException e) {
//            e.printStackTrace();
        }
        /**
         * 设置TriggerBean
         */
        ValueConditionBean valueConditionBean;
        ArrayList<ValueConditionBean> valueConditionBeans;
        TriggerBean triggerBean;
        try {
            jsonTriggers = jsonObject.getJSONObject("triggers");
            this.triggers = new HashMap<String, TriggerBean>();
            Iterator it = jsonTriggers.keys();
            while (it.hasNext()) {
                String key = (String) it.next();
                JSONArray array = jsonTriggers.getJSONArray(key);
                triggerBean = new TriggerBean();
                valueConditionBeans = new ArrayList<ValueConditionBean>();
                for (int i = 0; i < array.length(); i++) {
                    JSONObject jsonobject = array.getJSONObject(i);
                    valueConditionBean = new ValueConditionBean();
                    valueConditionBean.setDuaration(jsonobject.getInt("duration"));
                    valueConditionBean.setField(jsonobject.getString("field"));
                    valueConditionBean.setOp(jsonobject.getString("op"));
                    if (jsonobject.getString("op").equals("notin")) {
                        JSONArray jsonArray = jsonobject.getJSONArray("threshold_list");
                        valueConditionBean.setThresholdList(jsonArray);
                    } else if (jsonobject.getString("op").equals(">") || jsonobject.getString("op").equals("<") || jsonobject.getString("op").equals("=")) {
                        valueConditionBean.setThreshold(jsonobject.getDouble("threshold"));
                    } else {

                    }
                    valueConditionBeans.add(valueConditionBean);
                }
                triggerBean.setAddress(key);
                triggerBean.setValueConditionBeans(valueConditionBeans);
                this.triggers.put(key, triggerBean);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /**
         * 设置ArrayList<CommandBean> commands;
         */
        ArrayList<CommandBean> commands;
        CommandBean commandBean;
        JSONArray jsonRootCommands;
        JSONObject jsonRootCommand;
        JSONArray jsonCommands;
        JSONObject jsonCommand;
        ArrayList<ActionBean> command;
        ActionBean actionBean;
        try {
            jsonRootCommands = jsonObject.getJSONArray("commands");
            commands = new ArrayList<CommandBean>();
            for (int i = 0; i < jsonRootCommands.length(); i++) {
                jsonRootCommand = (JSONObject) jsonRootCommands.get(i);
                commandBean = new CommandBean();
                String type = jsonRootCommand.getString("type");
                if (type.equals("sleep")) {
                    commandBean.setOrder(jsonRootCommand.getInt("order"));
                    commandBean.setType(jsonRootCommand.getString("type"));
                    commandBean.setValue(jsonRootCommand.getInt("value"));
                    commands.add(commandBean);
                } else if (type.equals("commands")) {
                    commandBean.setType(jsonRootCommand.getString("type"));
                    commandBean.setOrder(jsonRootCommand.getInt("order"));
                    jsonCommands = jsonRootCommand.getJSONArray("commands");
                    command = new ArrayList<ActionBean>();
                    for (int j = 0; j < jsonCommands.length(); j++) {
                        actionBean = new ActionBean();
                        jsonCommand = (JSONObject) jsonCommands.get(j);
                        actionBean.setOrder(jsonCommand.getInt("order"));
                        actionBean.setField(jsonCommand.getString("field"));
                        actionBean.setValue(jsonCommand.getDouble("value"));
                        actionBean.setAddress(jsonCommand.getString("address"));
                        command.add(actionBean);
                    }
                    commandBean.setCommand(command);
                    commands.add(commandBean);
                } else if (type.equals("scene")) {
                    commandBean.setType("scene");
                    commandBean.setOrder(jsonRootCommand.getInt("order"));
                    commandBean.setScene_id(jsonRootCommand.getString("id"));
                    commands.add(commandBean);
                }
            }
            this.commands = commands;
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    protected RuleBean(Parcel in) {
        this.pns = in.readString();
        this.id = in.readString();
        this.title = in.readString();
        this.icon_data = in.readString();
        this.enabled = in.readInt();
        this.repeat_type = in.readInt();
        this.start = in.readString();
        this.end = in.readString();
        this.weekdays = in.readInt();
        this.place = in.readString();
        this.triggers = (HashMap<String, TriggerBean>) in.readSerializable();
        this.commands = new ArrayList<CommandBean>();
        in.readList(this.commands, List.class.getClassLoader());
    }
    /*
     * @param jsonObject
     */

    public int getPnsInterval() {
        return pnsInterval;
    }

    public void setPnsInterval(int pnsInterval) {
        this.pnsInterval = pnsInterval;
    }

    public JSONObject getUserdata() {
        return userdata;
    }

    public void setUserdata(JSONObject userdata) {
        this.userdata = userdata;
    }

    public String getIcon_type() {
        return icon_type;
    }

    public void setIcon_type(String icon_type) {
        this.icon_type = icon_type;
    }

    public String getPns() {
        return pns;
    }

    public void setPns(String pns) {
        this.pns = pns;
    }

    public HashMap<Integer, JSONArray> getTimeLine() {
        return timeLine;
    }

    public void setTimeLine(HashMap<Integer, JSONArray> timeLine) {
        this.timeLine = timeLine;
    }

    public String getUserTag() {
        return userTag;
    }

    public void setUserTag(String userTag) {
        this.userTag = userTag;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getIcon_data() {
        return icon_data;
    }

    public void setIcon_data(String icon_data) {
        this.icon_data = icon_data;
    }

    public int getEnabled() {
        return enabled;
    }

    public void setEnabled(int enabled) {
        this.enabled = enabled;
    }

    public int getRepeat_type() {
        return repeat_type;
    }

    public void setRepeat_type(int repeat_type) {
        this.repeat_type = repeat_type;
    }

    public String getStart() {
        return start;
    }

    public void setStart(String start) {
        this.start = start;
    }

    public String getEnd() {
        return end;
    }

    public void setEnd(String end) {
        this.end = end;
    }

    public int getWeekdays() {
        return weekdays;
    }

    public void setWeekdays(int weekdays) {
        this.weekdays = weekdays;
    }

    public String getPlace() {
        return place;
    }

    public void setPlace(String place) {
        this.place = place;
    }

    public HashMap<String, TriggerBean> getTriggers() {
        return triggers;
    }

    public void setTriggers(HashMap<String, TriggerBean> triggers) {
        this.triggers = triggers;
    }

    public ArrayList<CommandBean> getCommands() {
        return commands;
    }

    public void setCommands(ArrayList<CommandBean> commands) {
        this.commands = commands;
    }

    @Override
    public String toString() {
        return "RuleBean{" +
                "title='" + title + '\'' +
                ", icon_data='" + icon_data + '\'' +
                ", enabled=" + enabled +
                ", repeat_type=" + repeat_type +
                ", start='" + start + '\'' +
                ", end='" + end + '\'' +
                ", weekdays=" + weekdays +
                ", place='" + place + '\'' +
                ", triggers=" + triggers +
                ", commands=" + commands +
                ", id=" + this.id +
                '}';
    }

    public String triggersString() {
        return "";
    }

    /**
     * 转成删除指令参数
     * @return
     */
    public String toDeleteParams() {
        JSONObject jsonParams = new JSONObject();
        try {
            jsonParams.put("id", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonParams.toString();
    }
    /**
     * 转成指令参数
     * @return
     */
    public JSONObject toParams() {
        JSONObject jsonParams = new JSONObject();
        JSONObject jsonTriggers = new JSONObject();
        JSONArray jsonCommands = new JSONArray();
        JSONObject triggerCondition;
        JSONArray triggerConditions;
        JSONObject jsonCommand;
        JSONArray command;
        JSONObject jsonAction;
        try {
            jsonParams.put("title", title);
            jsonParams.put("icon_data", "default");
            jsonParams.put("enabled", enabled);
            jsonParams.put("repeat_type", repeat_type);
            jsonParams.put("weekdays", weekdays);
            jsonParams.put("icon_data", "icon_data");
            jsonParams.put("icon_type", "icon_type");
            jsonParams.put("place", place);
            jsonParams.put("pns_priority", pns_priority);
            try {
                userdata.put("start", start);
                userdata.put("end", end);
                jsonParams.put("user_data", userdata);
            } catch (Exception e) {

            }
            if (userTag == null)
                jsonParams.put("user_tag", "");
            else
                jsonParams.put("user_tag", userTag);
            if (timeLine != null) {
                HashMap<Integer, JSONArray> convertTimeline = new HashMap<>();
                JSONArray jsonArray = new JSONArray();
                Iterator iter = this.timeLine.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    int key = (int) entry.getKey();
                    JSONArray val = (JSONArray) entry.getValue();
                    jsonArray.put(val);
                    System.out.println("val=" + val.toString());
                }
                jsonParams.put("timeline", jsonArray);
            }
            if (!TextUtils.isEmpty(id))
                jsonParams.put("id", id);
            if (!TextUtils.isEmpty(pns))
                jsonParams.put("enabled_notifications", new JSONArray().put("pns"));
            else
                jsonParams.put("enabled_notifications", new JSONArray());
            Iterator iter = triggers.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                triggerConditions = new JSONArray();
                String key = (String) entry.getKey();
                TriggerBean val = (TriggerBean) entry.getValue();
                //针对水位增加报警频率 水位 1min 其余不设置默认为 5min
                String address = val.getAddress();
                if (!TextUtils.isEmpty(address)) {
                    if (SystemConstant.deviceBeanHashMap.get(address).getFunctype() == DeviceConstant.FUNCTYPE_WATERLEVER) {
                        jsonParams.put("pns_interval", 1);
                    }
                }
                ArrayList<ValueConditionBean> valueConditionBeans = val.getValueConditionBeans();
                for (ValueConditionBean valueConditionBean : valueConditionBeans) {
                    triggerCondition = new JSONObject();
                    triggerCondition.put("field", valueConditionBean.getField());
                    triggerCondition.put("op", valueConditionBean.getOp());
                    triggerCondition.put("duration", valueConditionBean.getDuaration());
                    if (valueConditionBean.getOp().equals("notin")) {
                        JSONArray jsonValues = valueConditionBean.getThresholdList();
                        double below = jsonValues.getDouble(1);
                        double above = jsonValues.getDouble(0);
                        JSONArray jsonArray = new JSONArray();
                        jsonArray.put(0, below);
                        jsonArray.put(1, above);
                        triggerCondition.put("threshold_list", jsonArray);
                    } else {
                        triggerCondition.put("threshold", valueConditionBean.getThreshold());
                    }
                    triggerConditions.put(triggerCondition);
                }
                jsonTriggers.put(key, triggerConditions);
            }
            jsonParams.put("triggers", jsonTriggers);
            for (CommandBean commandBean : commands) {
                jsonCommand = new JSONObject();
                command = new JSONArray();
                if (commandBean.getType().equals("sleep")) {
                    jsonCommand.put("type", commandBean.getType());
                    jsonCommand.put("order", commandBean.getOrder());
                    jsonCommand.put("value", commandBean.getValue());
                } else if (commandBean.getType().equals("commands")) {
                    jsonCommand.put("type", commandBean.getType());
                    jsonCommand.put("order", commandBean.getOrder());
                    ArrayList<ActionBean> actionBeans = commandBean.getCommand();
                    for (int j = 0; j < actionBeans.size(); j++) {
                        ActionBean actionBean = actionBeans.get(j);
                        jsonAction = new JSONObject();
                        jsonAction.put("order", actionBean.getOrder());
                        jsonAction.put("field", actionBean.getField());
                        jsonAction.put("value", actionBean.getValue());
                        jsonAction.put("address", actionBean.getAddress());
                        command.put(jsonAction);
                    }
                    jsonCommand.put("commands", command);
                } else if (commandBean.getType().equals("scene")) {
                    jsonCommand.put("type", commandBean.getType());
                    jsonCommand.put("order", commandBean.getOrder());
                    jsonCommand.put("id", commandBean.getScene_id());
                }
                jsonCommands.put(jsonCommand);
            }
            jsonParams.put("commands", jsonCommands);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonParams;
    }
}
